import { useState } from "react";
import { TemplateCard } from "./TemplateCard";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Search, Filter, Sparkles, Upload } from "lucide-react";
import { PBLCaseWorkshop } from "./PBLCaseWorkshop";
import { Dialog, DialogTrigger, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Card, CardContent } from "@/components/ui/card";
import { Star } from "lucide-react";
import { Textarea } from "@/components/ui/textarea";
import { CKEditor } from '@ckeditor/ckeditor5-react';
import ClassicEditor from '@ckeditor/ckeditor5-build-classic';
import { useState as useLocalState } from 'react';
import { MDXEditor, MDXEditorMethods } from '@mdxeditor/editor';
import React, { useRef } from 'react';
import mammoth from 'mammoth';
import { useNavigate } from 'react-router-dom';

interface Template {
  id: string;
  title: string;
  description: string;
  category: string;
  tags: string[];
  downloadCount: number;
  previewUrl?: string;
  isHot?: boolean;
  image?: string; // Added image field
  isNew?: boolean; // Added isNew field
  isFree?: boolean; // Added isFree field
  author?: string; // Added author field
  rating?: number; // Added rating field
  type?: 'word' | 'ppt'; // Added type field
  filePath?: string; // Added filePath field
}

// 用 Vite 的 import.meta.glob 动态加载 template 目录下所有文件
const templateFiles = import.meta.glob('/template/**/*.*', { as: 'url', eager: true });

// smartcourseware Home 页模板数据
const templateList: Template[] = [
  {
    id: '1',
    title: 'Interactive Math Quiz',
    author: '@mathprofessor',
    rating: 4.8,
    isNew: true,
    isFree: true,
    image: 'https://images.unsplash.com/photo-1503676382389-4809596d5290?auto=format&fit=crop&w=600&q=80',
    tags: ['Mathematics', 'Quiz'],
    description: 'Interactive educational content for mathematics learning. Perfect for classroom use and student engagement. This template includes dynamic quiz questions, real-time feedback, and progress tracking features.',
    category: 'Mathematics',
    downloadCount: 0,
    type: 'word',
    filePath: '/template/word/WPS_jiaoan.docx',
  },
  {
    id: '2',
    title: 'Physics Lab Simulation',
    author: '@physicslab',
    rating: 4.6,
    isNew: false,
    isFree: true,
    image: 'https://images.unsplash.com/photo-1465101046530-73398c7f28ca?auto=format&fit=crop&w=600&q=80',
    tags: ['Physics', 'Laboratory'],
    description: 'Virtual physics laboratory simulation for hands-on learning. Students can conduct experiments safely in a digital environment with realistic physics calculations and visual feedback.',
    category: 'Physics',
    downloadCount: 0,
    type: 'ppt', // 新增类型
  },
  {
    id: '3',
    title: 'Chemistry Experiment Guide',
    author: '@chemteacher',
    rating: 4.7,
    isNew: false,
    isFree: false,
    image: 'https://images.unsplash.com/photo-1517976487492-5750f3195933?auto=format&fit=crop&w=600&q=80',
    tags: ['Chemistry', 'Experiments'],
    description: 'Comprehensive chemistry experiment guide with step-by-step instructions, safety protocols, and interactive molecular visualizations. Perfect for both classroom and remote learning.',
    category: 'Chemistry',
    downloadCount: 0,
    type: 'word', // 新增类型
  },
  {
    id: '4',
    title: 'Biology Cell Structure',
    author: '@biologist',
    rating: 4.9,
    isNew: false,
    isFree: true,
    image: 'https://images.unsplash.com/photo-1464983953574-0892a716854b?auto=format&fit=crop&w=600&q=80',
    tags: ['Biology', 'Anatomy'],
    description: 'Interactive 3D cell structure exploration with detailed organelles, functions, and cellular processes. Students can zoom, rotate, and explore cellular components in detail.',
    category: 'Biology',
    downloadCount: 0
  },
  {
    id: '5',
    title: 'Programming Fundamentals',
    author: '@codeprofessor',
    rating: 4.5,
    isNew: true,
    isFree: false,
    image: 'https://images.unsplash.com/photo-1519389950473-47ba0277781c?auto=format&fit=crop&w=600&q=80',
    tags: ['Programming', 'Computer Science'],
    description: 'Learn programming fundamentals with interactive code examples, debugging exercises, and real-time code execution. Includes multiple programming languages and difficulty levels.',
    category: 'Programming',
    downloadCount: 0
  },
  {
    id: '6',
    title: 'Research Methodology',
    author: '@researcher',
    rating: 4.7,
    isNew: false,
    isFree: true,
    image: 'https://images.unsplash.com/photo-1461344577544-4e5dc9487184?auto=format&fit=crop&w=600&q=80',
    tags: ['Research', 'Methodology'],
    description: 'Comprehensive research methodology course covering qualitative and quantitative methods, data collection techniques, and statistical analysis tools.',
    category: 'Research',
    downloadCount: 0
  },
  {
    id: '7',
    title: 'History Timeline',
    author: '@historyteacher',
    rating: 4.8,
    isNew: false,
    isFree: true,
    image: 'https://images.unsplash.com/photo-1465101178521-c1a9136a3b99?auto=format&fit=crop&w=600&q=80',
    tags: ['History', 'Timeline'],
    description: 'Interactive historical timeline with multimedia content, primary sources, and contextual information. Students can explore historical events chronologically or thematically.',
    category: 'History',
    downloadCount: 0
  },
  {
    id: '8',
    title: 'Language Learning Module',
    author: '@linguist',
    rating: 4.6,
    isNew: false,
    isFree: true,
    image: 'https://images.unsplash.com/photo-1503676382389-4809596d5290?auto=format&fit=crop&w=600&q=80',
    tags: ['Language', 'Education'],
    description: 'Comprehensive language learning module with pronunciation guides, grammar exercises, vocabulary building, and cultural context. Supports multiple languages.',
    category: 'Language',
    downloadCount: 0
  },
  {
    id: '9',
    title: 'Data Science Workshop',
    author: '@datascientist',
    rating: 4.9,
    isNew: true,
    isFree: false,
    image: 'https://images.unsplash.com/photo-1513258496099-48168024aec0?auto=format&fit=crop&w=600&q=80',
    tags: ['Data Science', 'Analytics'],
    description: 'Hands-on data science workshop with real datasets, statistical analysis tools, and machine learning algorithms. Perfect for advanced students and professionals.',
    category: 'Data Science',
    downloadCount: 0
  },
  {
    id: '10',
    title: 'Art & Design Portfolio',
    author: '@artteacher',
    rating: 4.8,
    isNew: false,
    isFree: false,
    image: 'https://images.unsplash.com/photo-1465101046530-73398c7f28ca?auto=format&fit=crop&w=600&q=80',
    tags: ['Art', 'Design'],
    description: 'Digital art and design portfolio template with creative tools, design principles, and portfolio showcase features. Ideal for art students and creative professionals.',
    category: 'Art',
    downloadCount: 0
  },
  {
    id: '11',
    title: 'Literature Analysis',
    author: '@literatureprof',
    rating: 4.7,
    isNew: false,
    isFree: true,
    image: 'https://images.unsplash.com/photo-1519681393784-d120267933ba?auto=format&fit=crop&w=600&q=80',
    tags: ['Literature', 'Analysis'],
    description: 'Comprehensive literature analysis tools with text annotation, character analysis, theme exploration, and critical thinking exercises.',
    category: 'Literature',
    downloadCount: 0
  },
  {
    id: '12',
    title: 'Geography Interactive Map',
    author: '@geographer',
    rating: 4.6,
    isNew: true,
    isFree: true,
    image: 'https://images.unsplash.com/photo-1506744038136-46273834b3fb?auto=format&fit=crop&w=600&q=80',
    tags: ['Geography', 'Maps'],
    description: 'Interactive geographic mapping tool with political boundaries, physical features, climate data, and demographic information. Perfect for geography education.',
    category: 'Geography',
    downloadCount: 0
  }
];

const categories = [
  "Planning", 
  "Content Creation", 
  "Assessment", 
  "Student Engagement", 
  "Communication", 
  "Support & Differentiation", 
  "Admin & Reporting",
  "PBL Case Workshop"
];

const sortOptions = [
  { value: "popular", label: "Most Popular" },
  { value: "recent", label: "Most Recent" },
  { value: "alphabetical", label: "A-Z" },
  { value: "downloads", label: "Most Downloaded" }
];

// smartcourseware 英文标签
const smartcoursewareTags = [
  "Mathematics",
  "Quiz",
  "Physics",
  "Laboratory",
  "Programming",
  "Art",
  "Design",
  "Biology",
  "Chemistry",
  "History",
  "Language",
  "Education",
  "Data Science",
  "Analytics",
  "Research",
  "Timeline",
  "Computer Science",
  "Anatomy",
  "Experiments",
  "Methodology"
];

export function TemplateLibrary() {
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedCategory, setSelectedCategory] = useState("All Templates");
  const [sortBy, setSortBy] = useState("popular");
  const [filteredTemplates, setFilteredTemplates] = useState(templateList);
  const [uploadOpen, setUploadOpen] = useState(false);
  const [selectedFiles, setSelectedFiles] = useState<File[]>([]);
  const [detailOpen, setDetailOpen] = useState(false);
  const [detailTemplate, setDetailTemplate] = useState<Template | null>(null);
  // 2. 插入标签筛选和模板网格部分，替换原有模板展示部分
  const [selectedTag, setSelectedTag] = useState<string | null>(null);
  const [selectedTemplate, setSelectedTemplate] = useState<typeof templateList[0] | null>(null);
  const [isEditing, setIsEditing] = useState(false);
  const [editForm, setEditForm] = useState<any>(null);
  const navigate = useNavigate();

  const handleSearch = (term: string) => {
    setSearchTerm(term);
    filterAndSortTemplates(term, selectedCategory, sortBy);
  };

  const handleCategoryFilter = (category: string) => {
    setSelectedCategory(category);
    filterAndSortTemplates(searchTerm, category, sortBy);
  };

  const handleSortChange = (sort: string) => {
    setSortBy(sort);
    filterAndSortTemplates(searchTerm, selectedCategory, sort);
  };

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files) {
      setSelectedFiles(Array.from(e.target.files));
    }
  };

  // 修改 filterAndSortTemplates 逻辑，筛选时只考虑 smartcoursewareTags
  const filterAndSortTemplates = (search: string, category: string, sort: string, tag: string | null = selectedTag) => {
    let filtered = templateList;

    // Filter by category
    if (category !== "All Templates") {
      filtered = filtered.filter(template => template.category === category);
    }

    // Filter by tag（只用 smartcoursewareTags）
    if (tag) {
      filtered = filtered.filter(template => template.tags.some(t => t === tag));
    }

    // Filter by search term
    if (search) {
      filtered = filtered.filter(template => 
        template.title.toLowerCase().includes(search.toLowerCase()) ||
        template.description.toLowerCase().includes(search.toLowerCase()) ||
        template.tags.some(t => t.toLowerCase().includes(search.toLowerCase()))
      );
    }

    // Sort templates
    switch (sort) {
      case "popular":
        filtered = [...filtered].sort((a, b) => {
          if (a.isHot && !b.isHot) return -1;
          if (!a.isHot && b.isHot) return 1;
          return b.downloadCount - a.downloadCount;
        });
        break;
      case "downloads":
        filtered = [...filtered].sort((a, b) => b.downloadCount - a.downloadCount);
        break;
      case "alphabetical":
        filtered = [...filtered].sort((a, b) => a.title.localeCompare(b.title));
        break;
      case "recent":
        filtered = [...filtered].sort((a, b) => parseInt(b.id) - parseInt(a.id));
        break;
      default:
        break;
    }

    setFilteredTemplates(filtered);
  };

  // 标签点击时，调用新 filterAndSortTemplates
  const handleTagClick = (tag: string | null) => {
    setSelectedTag(tag);
    filterAndSortTemplates(searchTerm, selectedCategory, sortBy, tag);
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-2 flex-wrap justify-between mb-4">
        <div className="flex items-center gap-2 flex-wrap">
          {categories.map((category) => (
            <Button
              key={category}
              variant={selectedCategory === category ? "default" : "outline"}
              size="sm"
              onClick={() => handleCategoryFilter(category)}
            >
              {category}
            </Button>
          ))}
        </div>
        <Dialog open={uploadOpen} onOpenChange={setUploadOpen}>
          <DialogTrigger asChild>
            <Button variant="outline" size="sm" className="flex items-center gap-2">
              <Upload className="w-4 h-4" /> Upload
            </Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>Upload File or Folder</DialogTitle>
            </DialogHeader>
            <div className="space-y-4">
              <input
                type="file"
                multiple
                onChange={handleFileChange}
                className="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100"
              />
              <input
                type="file"
                multiple
                // @ts-ignore
                webkitdirectory=""
                // @ts-ignore
                directory=""
                onChange={handleFileChange}
                className="block w-full text-sm text-gray-500"
                style={{ marginTop: 8 }}
              />
              {selectedFiles.length > 0 && (
                <div className="mt-2 text-sm text-gray-700">
                  <b>Selected:</b>
                  <ul className="list-disc ml-5">
                    {selectedFiles.map((file) => (
                      <li key={file.name}>{file.name}</li>
                    ))}
                  </ul>
                </div>
              )}
            </div>
            <DialogFooter>
              <Button onClick={() => setUploadOpen(false)} type="button">Cancel</Button>
              <Button onClick={() => { setUploadOpen(false); setSelectedFiles([]); }} type="button">Upload</Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </div>
      {/* 分类内容渲染 */}
      {selectedCategory === "PBL Case Workshop" ? (
        <PBLCaseWorkshop simpleListMode />
      ) : (
        <>
          <div className="space-y-4">
            <div className="flex flex-col sm:flex-row gap-4 items-start sm:items-center justify-between">
              <h2 className="text-2xl font-bold text-gray-900">{selectedCategory}</h2>
              <div className="flex items-center gap-4">
                <span className="text-sm text-muted-foreground">Sort by</span>
                <Select value={sortBy} onValueChange={handleSortChange}>
                  <SelectTrigger className="w-48">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {sortOptions.map((option) => (
                      <SelectItem key={option.value} value={option.value}>
                        {option.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground w-4 h-4" />
              <Input
                placeholder={`Search ${selectedCategory}`}
                value={searchTerm}
                onChange={(e) => handleSearch(e.target.value)}
                className="pl-10 h-12 text-base"
              />
            </div>
          </div>
          <div className="mb-8">
            <div className="flex items-center gap-3 mb-4">
              <Sparkles className="w-6 h-6 text-blue-500" />
              <h3 className="text-xl font-bold text-gray-900">Popular Courseware Templates</h3>
            </div>
            <div className="flex flex-wrap gap-2 mb-6">
              <Button
                variant={selectedTag === null ? "default" : "outline"}
                size="sm"
                onClick={() => handleTagClick(null)}
                className="rounded-full"
              >
                All
              </Button>
              {smartcoursewareTags.map((tag) => (
                <Button
                  key={tag}
                  variant={selectedTag === tag ? "default" : "outline"}
                  size="sm"
                  onClick={() => handleTagClick(tag)}
                  className="rounded-full"
                >
                  {tag}
                </Button>
              ))}
            </div>
          </div>
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6 pb-12">
            {filteredTemplates.map((tpl) => (
              <Card
                key={tpl.id}
                className="rounded-2xl shadow-lg border-0 bg-white hover:shadow-2xl transition-all duration-300 hover:scale-105 overflow-hidden flex flex-col cursor-pointer"
                onClick={() => setSelectedTemplate(tpl)}
              >
                {/* 大图预览 */}
                <div className="relative aspect-video w-full bg-gray-100 overflow-hidden">
                  <img
                    src={tpl.image}
                    alt={tpl.title}
                    className="w-full h-full object-cover hover:scale-110 transition-transform duration-300"
                  />
                  {tpl.isNew && (
                    <span className="absolute top-3 right-3 bg-blue-500 text-white text-xs font-bold px-3 py-1 rounded-full shadow">New</span>
                  )}
                </div>
                <CardContent className="flex-1 flex flex-col p-4">
                  <div className="flex items-center gap-2 mb-2">
                    <span className="text-lg font-semibold text-gray-900 flex-1 truncate">{tpl.title}</span>
                    {tpl.isFree && (
                      <span className="bg-gray-100 text-gray-500 text-xs font-semibold px-2 py-0.5 rounded-full">Free</span>
                    )}
                  </div>
                  <div className="flex items-center gap-2 mb-2">
                    {/* smartcourseware 有作者字段，这里可用 tpl.author 或留空 */}
                    <span className="text-xs text-gray-500 truncate">{tpl.author || ''}</span>
                  </div>
                  <div className="flex items-center gap-2 mb-2">
                    {/* smartcourseware 有评分字段，这里可用 tpl.rating 或 downloadCount 近似 */}
                    <span className="text-xs text-yellow-500 flex items-center gap-1">★ {tpl.rating || tpl.downloadCount || 0}</span>
                  </div>
                  <div className="flex flex-wrap gap-1 mt-auto">
                    {tpl.tags.map((tag) => (
                      <Badge key={tag} variant="outline" className="text-xs px-2 py-0.5 border-gray-200">
                        {tag}
                      </Badge>
                    ))}
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
          <Dialog open={!!selectedTemplate} onOpenChange={() => { setSelectedTemplate(null); setIsEditing(false); }}>
            <DialogContent className="max-w-[75vw] max-h-[75vh] p-0 bg-white rounded-2xl overflow-hidden">
              {selectedTemplate && (
                <div className="flex flex-col h-full">
                  <div className="flex items-center justify-between p-6 border-b border-gray-200">
                    {isEditing ? (
                      <Input
                        className="text-2xl font-bold text-gray-900 bg-white border-0 p-0 focus:ring-0 focus:border-blue-400"
                        value={editForm?.title || ''}
                        onChange={e => setEditForm({ ...editForm, title: e.target.value })}
                      />
                    ) : (
                      <DialogTitle className="text-2xl font-bold text-gray-900">{selectedTemplate.title}</DialogTitle>
                    )}
                  </div>
                  <div className="flex-1 overflow-y-auto">
                    <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 p-6">
                      <div className="relative aspect-video w-full bg-gray-100 rounded-xl overflow-hidden">
                        <img
                          src={selectedTemplate.image}
                          alt={selectedTemplate.title}
                          className="w-full h-full object-cover"
                        />
                        {selectedTemplate.isNew && (
                          <span className="absolute top-4 right-4 bg-blue-500 text-white text-sm font-bold px-3 py-1 rounded-full shadow">New</span>
                        )}
                      </div>
                      <div>
                        {isEditing ? (
                          <>
                            {/* 编辑器区块：根据 type 渲染不同编辑器 */}
                            {selectedTemplate.type === 'word' && (
                              <div className="mb-4">
                                <label className="block text-sm font-medium mb-1">文档内容（富文本）</label>
                                {React.createElement(CKEditor as any, {
                                  editor: ClassicEditor,
                                  data: editForm?.description || '',
                                  onChange: (event: any, editor: any) => {
                                    const data = editor.getData();
                                    setEditForm({ ...editForm, description: data });
                                  }
                                })}
                              </div>
                            )}
                            {selectedTemplate.type === 'ppt' && (
                              <div className="mb-4">
                                <label className="block text-sm font-medium mb-1">PPT内容（Markdown/幻灯片）</label>
                                <MDXEditor
                                  ref={undefined}
                                  markdown={editForm?.description || ''}
                                  onChange={md => setEditForm({ ...editForm, description: md })}
                                  className="border rounded min-h-[200px]"
                                />
                              </div>
                            )}
                            {/* 标签和分类可选填 */}
                            <Input
                              className="mb-2"
                              value={editForm?.tags?.join(', ') || ''}
                              onChange={e => setEditForm({ ...editForm, tags: e.target.value.split(',').map((t:string)=>t.trim()) })}
                              placeholder="标签（逗号分隔）"
                            />
                            <Input
                              className="mb-2"
                              value={editForm?.category || ''}
                              onChange={e => setEditForm({ ...editForm, category: e.target.value })}
                              placeholder="分类"
                            />
                            <div className="flex gap-2 mt-4">
                              <Button className="flex-1 bg-blue-600 hover:bg-blue-700 text-white" onClick={() => {
                                setSelectedTemplate({ ...selectedTemplate, ...editForm });
                                setIsEditing(false);
                              }}>保存</Button>
                              <Button className="flex-1 bg-green-600 hover:bg-green-700 text-white" onClick={() => {
                                setSelectedTemplate({ ...selectedTemplate, ...editForm });
                                setIsEditing(false);
                                alert('已发布！');
                              }}>发布</Button>
                            </div>
                          </>
                        ) : (
                          <>
                            <div className="flex flex-wrap gap-2 mb-2">
                              {selectedTemplate.tags.map(tag => (
                                <Badge key={tag} variant="outline">{tag}</Badge>
                              ))}
                            </div>
                            {/* 只读内容区块：根据 type 渲染不同内容 */}
                            {selectedTemplate.type === 'word' ? (
                              <div className="prose prose-sm max-w-none mb-2" dangerouslySetInnerHTML={{ __html: selectedTemplate.description }} />
                            ) : selectedTemplate.type === 'ppt' ? (
                              <div className="bg-gray-50 border rounded p-2 text-xs text-gray-700 mb-2 whitespace-pre-line" style={{minHeight:80}}>{selectedTemplate.description}</div>
                            ) : (
                              <p className="text-gray-700 text-base mb-2">{selectedTemplate.description}</p>
                            )}
                            <div className="flex items-center gap-2 mb-2">
                              <span className="text-xs text-gray-400">{selectedTemplate.category}</span>
                              <span className="text-xs text-yellow-500 flex items-center gap-1">★ {selectedTemplate.rating || selectedTemplate.downloadCount || 0}</span>
                            </div>
                            <div className="pt-4">
                              {/* 如果是第一个卡片，编辑按钮直接跳转到金山文档（WPS云文档） */}
                              {selectedTemplate.id === '1' ? (
                                <Button className="w-full bg-blue-600 hover:bg-blue-700 text-white" onClick={() => {
                                  navigate('/wps-edit');
                                }}>
                                  edit
                                </Button>
                              ) : (
                                <Button className="w-full bg-blue-600 hover:bg-blue-700 text-white" onClick={async () => {
                                  setIsEditing(true);
                                  setEditForm({
                                    title: selectedTemplate.title,
                                    description: selectedTemplate.description,
                                    tags: selectedTemplate.tags,
                                    category: selectedTemplate.category
                                  });
                                }}>
                                  编辑
                                </Button>
                              )}
                            </div>
                          </>
                        )}
                      </div>
                    </div>
                  </div>
                </div>
              )}
            </DialogContent>
          </Dialog>
          {filteredTemplates.length === 0 && (
            <div className="text-center py-12">
              <p className="text-muted-foreground mb-4">No matching templates found</p>
              <Button 
                variant="outline" 
                onClick={() => {
                  setSearchTerm("");
                  setSelectedCategory("Planning");
                  setSortBy("popular");
                  setFilteredTemplates(templateList);
                }}
                className="mt-4"
              >
                Clear Filters
              </Button>
            </div>
          )}
        </>
      )}
    </div>
  );
}
